package com.smy.baseutil.entity;

import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.springframework.beans.BeanUtils;

public class BaseEntity implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6041159419802158998L;

	private transient ThreadLocal<BaseEntity> vistor = new ThreadLocal<>();

	/**
	 * 类名称
	 */
	private String simpleName = getClass().getSimpleName();

	@Override
	public String toString() {
		if (vistor.get() == null) {
			vistor.set(this);
			try {
				return toString0();
			} finally {
				vistor.set(null);
			}
		}
		return simpleName + "@" + Integer.toHexString(hashCode());
	}

	private String toString0() {
		Method m;
		boolean isEnd = true;
		Object[] params = new Object[0];
		//StringBuilder sb = new StringBuilder(simpleName + "{");
		StringBuilder sb = new StringBuilder("{");
		try {
			PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(getClass());
			for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
				if (!"class".equals(propertyDescriptor.getName())) {
					m = propertyDescriptor.getReadMethod();
					if (!m.isAccessible()) {
						m.setAccessible(true);
					}
					Object result = m.invoke(this, params);
					if (!isEnd) {
						sb.append(",");
					} else {
						isEnd = false;
					}
					Field feild = this.getClass().getDeclaredField(propertyDescriptor.getName());
					Secret annotation = feild.getAnnotation(Secret.class);
					if (annotation == null) {
						sb.append("\"" + propertyDescriptor.getName() + "\"").append(":\"" + result + "\"");
					} else {
						sb.append("\"" + propertyDescriptor.getName() + "\"").append(":\"******\"");
					}

					m.setAccessible(false);
				}
			}
			sb.append("}");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

}
